<script setup>
  import { ref, reactive, watch, createVNode, nextTick } from "vue";
  import store from "@/store";
  import {
    WarningFilled,
    PlusCircleOutlined,
    SwapOutlined,
    PlusOutlined,
    MoreOutlined,
    ExclamationCircleOutlined
  } from "@ant-design/icons-vue";
  import { Form, Modal, message } from "ant-design-vue";
  import AddTeam from "@/components/AddTeam/index.vue";
  import WikiList from './wikiList.vue';
  import request from "@/common/utils/request";
  import { useRouter } from "vue-router";
  import utils from "@/common/utils/utils";

  const useForm = Form.useForm;
  const router = useRouter();

  const showPage = ref(false)
  const notMember = ref(false)
  const addTeamVisible = ref(false)
  const loginVisible = ref(false)
  const editWikiVisible = ref(false)
  const editWikiId = ref(null)
  const currentCate = ref(null)
  const cateList = ref([])
  const wikiListRedraw = ref(false)

  const wikiFormRef = reactive({
    name: "",
    token: ""
  })

  const wikiRulesRef = reactive({
    name: [{ required: true, message: "知识库名称不能为空" }],
  });

  const {
    resetFields: wikiResetFields,
    validate: vikiVilidate,
    validateInfos: wikiValidateInfos,
  } = useForm(wikiFormRef, wikiRulesRef);

  watch(
    editWikiVisible,
    (val) => {
      if (!val) {
        wikiResetFields();
      }
    }
  );

  const editCate = (record) => {
    editWikiId.value = null;

    wikiFormRef.name = "";
    wikiFormRef.token = "";

    if (record && record.id) {
      editWikiId.value = record.id;

      wikiFormRef.name = record.name;
      wikiFormRef.token = record.token;
    }

    editWikiVisible.value = true;
  }

  const onSubmitWiki = () => {
    if (vikiVilidate()) {
      if (!wikiFormRef.name) {
        message.error("知识库名称不能为空");
        return;
      }

      let requestType = "post";
      let url = "/user/team/wiki";
      let params = {
        name: wikiFormRef.name,
        token: wikiFormRef.token,
        team_id: store.state.user.teamId,
      };
      if (editWikiId.value) {
        requestType = "put";
        url = "/user/team/wiki";
        params.id = editWikiId.value;
      }
      request[requestType]("/work_ai", url, {
        ...params,
      }).then((res) => {
        message.success("保存成功");
        editWikiVisible.value = false;
        getCateList();
      });
    }
  }

  const getCateList = () => {
    request
      .get("/work_ai", "/user/team/wiki", {
        page: 1,
        pageSize: 9999,
        team_id: store.state.user.teamId,
      })
      .then((res) => {
        cateList.value = res.list;
        if (res.list.length > 0) {
          currentCate.value = res.list[0];
        }
      });
  }
  
  const loginCallback = () => {
    loginVisible.value = false;
    router.go(0);
  }

  const addTeamSuccess = () => {
    addTeamVisible.value = false;
    init();
  }

  const onCateClick = (item) => {
    if (currentCate.value.id == item.id) {
      return;
    }
    currentCate.value = item;
  }

  const deleteCate = (id) => {
      Modal.confirm({
        title: () => `确定要删除吗？`,
        icon: () => createVNode(ExclamationCircleOutlined),
        centered: true,
        onOk() {
          request
            .del("/work_ai", "/user/team/wiki", {
              id,
            })
            .then((res) => {
              message.success("删除成功");
              getCateList();
            });
        },
      });
    };

  const init = () => {
    if (store.state.user.teamId) {
      notMember.value = false;
      getCateList();
    } else {
      notMember.value = true;
    }
  }

  utils.checkLogin().then((isLogin) => {
    if (!isLogin) {
      loginVisible.value = true;
      return;
    }
    showPage.value = true;
    init();
  })

  watch(
    () => store.state.user.teamId,
    () => {
      init();
    }
  )

  watch(currentCate, (val) => {
    wikiListRedraw.value = true;

    nextTick(() => {
      wikiListRedraw.value = false;
    })
  })
</script>

<template>
  <div class="wiki-list">
    <template v-if="showPage">
      <template v-if="notMember">
        <a-card :bordered="false" style="margin: 0 20px">
          <div class="flex flex-col align-center py-30">
            <WarningFilled style="color: #faad14; font-size: 64px" />
            <div class="mt-20 fs-24">此能力仅团队成员可用</div>
            <div class="mt-10 text-gray-6">当前身份：个人</div>
            <a-row class="mt-20 flex justify-center">
              <a-button
                type="primary"
                style="border-radius: 6px"
                @click="changeTeamPopoverVisible(true)"
              >
                <template #icon><SwapOutlined /></template>
                切换团队
              </a-button>
              <a-button
                type="primary"
                class="ml-20"
                style="border-radius: 6px"
                @click="addTeamVisible = true"
              >
                <template #icon><PlusCircleOutlined /></template>
                创建团队
              </a-button>
            </a-row>
          </div>
        </a-card>
      </template>
      <template v-else>
        <div class="content">
          <div class="left">
            <div
              style="
                display: flex;
                justify-content: space-between;
                align-items: center;
              "
            >
              <div>企业知识库</div>
              <a-button
                type="link"
                style="padding: 0; margin: 0"
                @click="editCate"
              >
                <template #icon><PlusOutlined /></template>
                添加知识库
              </a-button>
            </div>
            <div class="cate-list beauty-scroller-bar">
              <template v-if="cateList.length > 0">
                <div
                  class="cate-list-item"
                  v-for="(item, index) of cateList"
                  :key="index"
                  @click="onCateClick(item)"
                  :class="
                    currentCate.id == item.id ? 'cate-list-item-current' : ''
                  "
                >
                  <span>{{ item.name }}</span>
                  <a-dropdown :trigger="['click']" v-if="!item.is_root">
                    <span
                      class="ant-dropdown-link"
                      @click.stop
                      style="padding: 0 5px"
                    >
                      <MoreOutlined />
                    </span>
                    <template #overlay>
                      <a-menu>
                        <a-menu-item key="0">
                          <a-button
                            type="link"
                            style="
                              width: 100%;
                              text-align: center;
                              padding: 0 16px;
                              margin: 0;
                            "
                            @click="editCate(item)"
                            >编辑知识库</a-button
                          >
                        </a-menu-item>
                        <a-menu-item key="1" v-if="cateList.length > 1">
                          <a-button
                            type="link"
                            danger
                            style="
                              width: 100%;
                              text-align: center;
                              padding: 0 16px;
                              margin: 0;
                            "
                            @click="deleteCate(item.id)"
                            >删除知识库</a-button
                          >
                        </a-menu-item>
                      </a-menu>
                    </template>
                  </a-dropdown>
                </div>
              </template>
            </div>
          </div>
          <div class="right beauty-scroller-bar">
            <wiki-list :wikiId="currentCate.id" v-if="currentCate && (! wikiListRedraw)"></wiki-list>

            <div class="w-full h-full flex justify-center align-center" v-else>
              <a-spin></a-spin>
            </div>
          </div>
        </div>
      </template>
    </template>

    <AddTeam
      :visible="addTeamVisible"
      @onClose="addTeamVisible = false"
      @success="addTeamSuccess"
    />

    <LoginModal
      :visible="loginVisible"
      @onClose="loginVisible = false"
      @loginCallback="loginCallback"
    />

    <a-modal
      :visible="editWikiVisible"
      :title="editWikiId ? '编辑知识库' : '新增知识库'"
      centered
      :width="400"
      @cancel="editWikiVisible = false"
      @ok="onSubmitWiki"
      ok-text="保存"
      :zIndex="1002"
    >
      <div class="modal-content">
        <a-form :model="wikiFormRef" layout="vertical">
          <a-form-item label="知识库名称" v-bind="wikiValidateInfos.name">
            <a-input
              v-model:value="wikiFormRef.name"
              placeholder="请填写知识库名称"
            />
          </a-form-item>
        </a-form>
      </div>
    </a-modal>
  </div>
</template>

<style lang="less" scoped>
  .wiki-list {
  width: 100%;
  height: 100%;
  padding: 20px;

  .content {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: space-between;

    .left {
      width: 260px;
      height: 100%;
      background-color: #fff;
      padding: 10px 20px;
      border-radius: 4px;

      .cate-list {
        width: 100%;
        height: calc(100% - 52px);
        overflow: hidden auto;
        margin: 10px 0;

        .cate-list-item {
          padding: 8px 0 8px 10px;
          margin-top: 5px;
          border-radius: 4px;
          cursor: pointer;
          display: flex;
          justify-content: space-between;
          align-items: center;
        }

        .cate-list-item-current {
          background-color: #f7f0ff;
        }
      }
    }

    .right {
      width: calc(100% - 280px);
      height: 100%;
      background-color: #fff;
      padding: 10px 20px;
      border-radius: 4px;
      overflow: hidden auto;
    }
  }
}
</style>
